//
//  KLSdk.m
//  WebRTCDemo_iOS
//
//  Created by szblsx2 on 2020/3/5.
//  Copyright © 2020 szblsx2. All rights reserved.
//

#import "KLSdk.h"
#import "KLEngine.h"
#import "KLRePlayTool.h"

@interface KLSdk ()<engineDelegate>
//连接器
@property (nonatomic, strong) KLEngine *mKLEngine;
//录屏类
//@property (nonatomic, strong) KLRePlayTool *replayTool;
//日志管理
@property (nonatomic, strong) RTCFileLogger *flieLogger;

@end

@implementation KLSdk

static KLSdk *shareInstance;

+ (instancetype)shared{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[self alloc] init];
    });
    return shareInstance;
}

- (instancetype)init{
    if (self = [super init]) {
        if (!_mKLEngine) {
            _mKLEngine = [[KLEngine alloc] init];
            _mKLEngine.delegate = self;
        }
        //        if (!_replayTool) {
        //            _replayTool = [[KLRePlayTool alloc] init];
        //        }
    }
    return self;
}

#pragma mark - Public Method

/** 初始化SDK */
- (void)initSDKWithServer:(NSString *)server port:(nonnull NSString *)port
{
    [self.mKLEngine initEngineWithServer:server port:port];
}

/**设置turn转发服务器地址*/
- (void)setupIceServers:(NSArray<RTCIceServer *> *)iceServers
{
    [self.mKLEngine setupIceServers:iceServers];
}

/**进入会议(创建、加入)*/
- (void)enterMeetingWithRoomId:(NSString *)roomId myInfo:(KLMeetUser *)myInfo completion:(void (^)(BOOL))completion
{
    [self startWebRTCFileLogger];
    [self.mKLEngine enterMeetingWithRoomId:roomId
                                    myInfo:myInfo
                                completion:completion];
}


/**离开会议*/
- (void)leaveMeeting
{
    [self.mKLEngine leaveMeeting];
    [self.mKLEngine freeSdk];
    [self stopWebRTCFileLogger];
}

/**根据用户id选择订阅流*/
- (void)chooseMediaSoucesWithUserIds:(NSArray *)userIds
{
    [self.mKLEngine chooseMediaSoucesWithUserIds:userIds];
}

/**是否打开摄像头*/
- (void)turnOnCamera:(BOOL)open
{
    [self.mKLEngine turnOnCamera:open];
}

/**切换前后置摄像头*/
- (void)switchCamera
{
    [self.mKLEngine switchCamera];
}

/**是否打开麦克风*/
- (void)turnOnMicrophone:(BOOL)open
{
    [self.mKLEngine turnOnMicrophone:open];
}

/**是否扬声器*/
- (void)whetherToOpenLoudspeaker:(BOOL)open
{
    [self.mKLEngine whetherToOpenLoudspeaker:open];
}


///**开启录屏*/
//- (void)startRecording:(void (^)(NSError *error))callBack
//{
//    [self.replayTool startRecording:^(NSError * _Nonnull error) {
//        callBack(error);
//    }];
//}
//
//
///**停止录屏*/
//- (void)stopRecording:(void(^)(NSString *filePath, NSError *error))callBack
//{
//    [self.replayTool stopRecording:^(NSString * _Nonnull filePath, NSError * _Nonnull error) {
//        callBack(filePath,error);
//    }];
//}

/** 发送自定义视频数据*/
- (void)sendVideoSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
    [self.mKLEngine sendVideoSampleBuffer:sampleBuffer];
}

/**会议广播*/
- (void)sendMeetingNotificationWithType:(KLNotifiType)notifiType targetUserId:(nonnull NSString *)targetUserId state:(BOOL)state
{
    [self.mKLEngine sendMeetingNotificationWithType:notifiType targetUserId:targetUserId state:state];
}

#pragma mark - engineDelegate

/** 获取到房间用户列表回调  */
- (void)respRoomUserList:(NSArray<KLMeetUser *> *)userList
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(respRoomUserList:)]) {
        [self.delegate respRoomUserList:userList];
    }
}

/**本地媒体回调*/
- (void)addLocalCapturerSession:(AVCaptureSession *)captureSession
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(addLocalCapturerSession:)]) {
        [self.delegate addLocalCapturerSession:captureSession];
    }
}

/**远端添加媒体回调*/
- (void)addRemoteMediaStream:(RTCMediaStream *)mediaStream streamId:(NSString *)streamId userId:(NSString *)userId
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(addRemoteMediaStream:streamId:userId:)]) {
        [self.delegate addRemoteMediaStream:mediaStream streamId:streamId userId:userId];
    }
}

/**远端移除媒体回调*/
- (void)removeRemoteMediaStreamWithStreamId:(NSString *)streamId userId:(NSString *)userId
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(removeRemoteMediaStreamWithStreamId:userId:)]) {
        [self.delegate removeRemoteMediaStreamWithStreamId:streamId userId:userId];
    }
}

/**新用户进入房间回调*/
- (void)respUserJoinRoom:(KLMeetUser *)newUser
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(respUserJoinRoom:)]) {
        [self.delegate respUserJoinRoom:newUser];
    }
}

/**房间用户离开回调*/
- (void)respUserLeaveWithUserId:(NSString *)userId
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(respUserLeaveWithUserId:)]) {
        [self.delegate respUserLeaveWithUserId:userId];
    }
}

/**会议广播回调*/
- (void)resMeetingNotificationWithType:(KLNotifiType)type targetUserId:(NSString *)targetUserId state:(BOOL)state
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(resMeetingNotificationWithType:targetUserId:state:)]) {
        [self.delegate resMeetingNotificationWithType:type targetUserId:targetUserId state:state];
    }
}

#pragma mark - Private Method

/**开启日志输出*/
- (void)startWebRTCFileLogger
{
    if (!_flieLogger) {
        BOOL createPath = YES;
        NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSString *dataFilePath = [cachesDirectory stringByAppendingPathComponent:@"LKRTCLogger"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataFilePath isDirectory:&createPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        _flieLogger = [[RTCFileLogger alloc] initWithDirPath:dataFilePath maxFileSize:1024*1024*1024];
        _flieLogger.severity = RTCLoggingSeverityInfo;
    }
    [_flieLogger start];
}

/**停止日志输出*/
- (void)stopWebRTCFileLogger
{
    if (_flieLogger) {
        [_flieLogger stop];
    }
}

@end
